import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import {
  Select,
  Button,
  Table,
  Input,
  message,
  TreeSelect,
  DatePicker,
  Modal,
} from "antd";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  MinusCircleOutlined,
  PlusCircleOutlined,
} from "@ant-design/icons";
import "./index.scss";
import { text_check, post_axios, format_time } from "../../utils";
import dayjs from "dayjs";

export default function AccountSplitPlan(props) {
  const { t } = useTranslation();
  const [tableHeight, setTableHeight] = useState(0);
  const { actions, setSpinning } = props;
  const { RangePicker } = DatePicker;
  let { menu_action, user_power_lang, username, user_grade } = actions;
  user_power_lang = JSON.parse(user_power_lang);

  // 国内国外判断
  const session_company = sessionStorage.getItem("company");
  let localStorage_company = JSON.parse(localStorage.getItem("choose_company"));
  const local_company_object =
    localStorage_company &&
    localStorage_company[username] &&
    localStorage_company[username]
      ? localStorage_company[username]
      : "";

  const [page, setPage] = useState(1);
  const [rows, setRows] = useState(20);
  const [total, setTotal] = useState(0);
  const [account_split_plan_name, setAccount_split_plan_name] = useState("");
  const [account_split_plan_status, setAccount_split_plan_status] =
    useState("ENABLE");
  const [com_ids_par, setCom_ids_par] = useState([]);
  const [account_split_plan_list, setAccount_split_plan_list] = useState([]);

  const getData = async (newPage, newRows) => {
    let upMsg = {
      page: newPage ? newPage : page,
      rows: newRows ? newRows : rows,
      company_id: local_company_object.id,
      company: local_company_object.company,
      name: account_split_plan_name,
      status: account_split_plan_status,
      com_ids_par: com_ids_par.map((item) => item.value),
    };
    setSpinning(true);
    let res = await post_axios("account_split_plan", "m_query", upMsg);
    setSpinning(false);
    if (!res) return;
    setAccount_split_plan_list(res.data_rows.rows);
    setTotal(res.data_rows.total);
  };
  const columns = [
    {
      dataIndex: "idx",
      align: "center",
      width: 40,
      render: (_, record, index) => <>{index + 1}</>,
    },
    {
      title: t("assets.strategy_name"),
      dataIndex: "plan_name",
      align: "center",
    },
    {
      title: t("system_manager.organization"),
      dataIndex: "com",
      align: "center",
    },
    {
      title: t("common.status"),
      align: "center",
      width: 100,
      render: (_, record) => (
        <>
          {record.status === "ENABLE" ? (
            <span>{t("common.enable")}</span>
          ) : (
            <span style={{ color: "red" }}>{t("common.disable")}</span>
          )}
        </>
      ),
    },
    {
      title: t("market.operator"),
      dataIndex: "username",
      align: "center",
    },
    {
      title: t("system_manager.create_time"),
      dataIndex: "u_time",
      align: "center",
    },
  ];

  // 分页器
  const pageOnChange = async (page, pageSize) => {
    setPage(page);
    setRows(pageSize);
    initData(page, pageSize);
  };

  // 用户数据行点击
  const [clickRowKey, setClickRowKey] = useState("");
  const [clickRow, setclickRow] = useState({});

  const tableRowClick = (row) => {
    setClickRowKey(row.plan_id);
    setclickRow(row);
    setClicked_plan_mch_id("");
    setClicked_plan_mch_obj({});
    get_account_split_plan_mch_data(row);
  };

  const search_data = () => {
    setPage(1);
    initData(1);
  };

  const initData = (page, rows) => {
    setClickRowKey("");
    setclickRow([]);
    setClicked_plan_mch_id("");
    setClicked_plan_mch_obj({});
    setAccount_split_plan_mch_list([]);
    getData(page, rows);
  };

  const [clicked_plan_mch_id, setClicked_plan_mch_id] = useState("");
  const [clicked_plan_mch_obj, setClicked_plan_mch_obj] = useState({});
  const [account_split_plan_mch_list, setAccount_split_plan_mch_list] =
    useState();

  const get_account_split_plan_mch_data = async (value) => {
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      plan_id: value ? value.plan_id : clickRowKey,
    };
    setSpinning(true);
    let res = await post_axios("account_split_plan", "m_query_mch", upMsg);
    setSpinning(false);
    if (!res) return;
    setAccount_split_plan_mch_list(res.data_rows.rows);
  };

  const mchColumns = [
    {
      dataIndex: "idx",
      align: "center",
      width: 40,
      render: (_, record, index) => <>{index + 1}</>,
    },
    {
      title: t("assets.commission_name"),
      dataIndex: "plan_mch_name",
      align: "center",
    },
    {
      title: t("system_manager.merchant"),
      dataIndex: "mch",
      align: "center",
    },
    {
      title: t("assets.percentage"),
      align: "center",
      render: (_, record) => <>{record.share_proportion}%</>,
    },
    {
      title: t("system_manager.begin_time"),
      dataIndex: "bdate",
      align: "center",
    },
    {
      title: t("system_manager.end_time"),
      dataIndex: "edate",
      align: "center",
    },
  ];
  const account_plan_mch_row_click = (row) => {
    setClicked_plan_mch_id(row.plan_mch_id);
    setClicked_plan_mch_obj(row);
  };

  // 添加/修改
  const [edit_type, setEdit_type] = useState("");
  const [editDialogshow, setEditDialogshow] = useState(false);
  const [editDialogtitle, setEditDialogtitle] = useState("");

  const [edit_account_split_plan_name, setEdit_account_split_plan_name] =
    useState("");
  const [edit_account_split_plan_status, setEdit_account_split_plan_status] =
    useState("ENABLE");
  const [edit_account_split_plan_com_id, setEdit_account_split_plan_com_id] =
    useState("");

  const edit_project_dialog_show = async (value) => {
    setEdit_type(value);
    if (value === "add") {
      setEditDialogshow(true);
      setEditDialogtitle(t("common.add") + " " + t("market.mch"));
      setEdit_account_split_plan_name("");
      setEdit_account_split_plan_status("ENABLE");
      setEdit_account_split_plan_com_id("");
    } else {
      if (clickRowKey === "") {
        message.warning({
          content: t("market.select_mch"),
        });
        return;
      }
      setEditDialogshow(true);
      setEditDialogtitle(t("common.change") + " " + t("market.mch"));
      const { plan_name, status, com_id } = clickRow;

      setEdit_account_split_plan_name(plan_name);
      setEdit_account_split_plan_status(status);
      setEdit_account_split_plan_com_id(com_id);
    }
  };

  const editConfirm = async () => {
    if (edit_account_split_plan_name === "") {
      message.warning({
        content: t("market.enter_mch_name"),
      });
      return;
    }
    if (edit_account_split_plan_com_id === "") {
      message.warning({
        content: t("market.select_organization"),
      });
      return;
    }

    let upMsg = {
      com_id: edit_account_split_plan_com_id,
      name: edit_account_split_plan_name,
      status: edit_account_split_plan_status,
      company_id: local_company_object.id,
      company: local_company_object.company,
    };

    let action = "m_add";
    if (edit_type === "change") {
      action = "m_modify";
      upMsg["plan_id"] = clickRowKey;
    }
    setSpinning(true);
    let res = await post_axios("account_split_plan", action, upMsg);
    setSpinning(false);
    if (!res) return;
    message.success({
      content: editDialogtitle + " " + t("common.successfully"),
    });
    setEditDialogshow(false);
    search_data();
  };

  const [edit_plan_mch_show, setEdit_plan_mch_show] = useState(false);
  const [edit_plan_mch_title, setEdit_plan_mch_title] = useState();
  const [edit_plan_mch_type, setEdit_plan_mch_type] = useState("add");
  const [edit_plan_mch_name, setEdit_plan_mch_name] = useState("");
  const [edit_mch_arr, setEdit_mch_arr] = useState([
    {
      mch_id: "",
      share_proportion: "",
    },
  ]);
  const [edit_plan_mch_time, setEdit_plan_mch_time] = useState([]);
  const edit_plan_mch_dialog = (value) => {
    if (clickRowKey === "") {
      message.warning({
        content: t("assets.choose_an_account"),
      });
      return;
    }
    setEdit_plan_mch_type(value);
    if (value === "add") {
      setEdit_plan_mch_title(t("common.add") + " " + t("assets.commission"));
      setEdit_plan_mch_name("");
      setEdit_mch_arr([
        {
          mch_id: "",
          share_proportion: "",
        },
      ]);
      setEdit_plan_mch_time("");
      setEdit_plan_mch_show(true);
    } else {
      if (clicked_plan_mch_id === "") {
        message.warning({
          content: t("system_manager.choose_one_project"),
        });
        return;
      }
      setEdit_plan_mch_title(t("common.change") + " " + t("assets.commission"));
      let newArr = [];
      account_split_plan_mch_list.forEach((item) => {
        if (item.plan_mch_id == clicked_plan_mch_id) {
          newArr.push({
            mch_id: item.mch_id,
            share_proportion: item.share_proportion,
          });
        }
      });
      setEdit_mch_arr(newArr);
      console.log(edit_mch_arr);
      const { bdate, edate, plan_mch_name } = clicked_plan_mch_obj;
      console.log(bdate);
      console.log(dayjs(bdate));
      setEdit_plan_mch_name(plan_mch_name);
      setEdit_plan_mch_time([dayjs(bdate), dayjs(edate)]);
      setEdit_plan_mch_show(true);
    }
  };
  const editMchChange = (value, item, index) => {
    const newArr = edit_mch_arr;
    newArr[index]["mch_id"] = value;
  };
  const editProportionChange = (value, item, index) => {
    const newArr = edit_mch_arr;
    newArr[index]["share_proportion"] = value;
  };
  const add_mch_child = () => {
    setEdit_mch_arr([
      ...edit_mch_arr,
      {
        mch_id: "",
        share_proportion: "",
      },
    ]);
  };
  const remove_mch_child = (value) => {
    if (edit_mch_arr.length <= 1) {
      message.warning({
        content: t("assets.at_least_one_mch"),
      });
      return;
    } else {
      edit_mch_arr.splice(value, 1);
    }
  };
  const edit_plan_mch_confirm = async () => {
    if (edit_plan_mch_name === "") {
      message.warning({
        content: t("assets.enter_commission_name"),
      });
      return;
    }
    if (edit_plan_mch_time.length !== 2) {
      message.warning({
        content: t("assets.choose_begin_time"),
      });
      return;
    }

    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      plan_id: clickRowKey,
      plan_mch_name: edit_plan_mch_name,
      mch_ids: edit_mch_arr,
      bdate: format_time(edit_plan_mch_time[0], "time_date"),
      edate: format_time(edit_plan_mch_time[1], "time_date"),
    };
    let action = "m_add_mch";
    if (edit_plan_mch_type == "change") {
      action = "m_modify_mch";
      upMsg["plan_mch_id"] = clicked_plan_mch_id;
    }
    setSpinning(true)
    let res = await post_axios("account_split_plan", action, upMsg);
    setSpinning(false)
    if (!res) return;
    message.success({
      content: editDialogtitle + " " + t("common.successfully"),
    });
    setEdit_plan_mch_show(false);
    setClicked_plan_mch_id("");
    setClicked_plan_mch_obj({});
    get_account_split_plan_mch_data();
  };

  // 获取组织列表
  const [com_list, setCom_list] = useState([]);
  const get_com_data = async () => {
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      op_type: "list_com_id",
    };
    let res = await post_axios("admin_oneself", "m_query", upMsg);
    if (!res) return;
    setCom_list(res.data_rows.rows);
  };
  // 筛选_获取商户列表
  const [mch_page, setMch_page] = useState(1);
  const [mch_list, setMch_list] = useState([]);
  const get_mch_data = async (newPage) => {
    let upMsg = {
      page: newPage ? newPage : mch_page,
      rows: 20,
      company_id: local_company_object.id,
      company: local_company_object.company,
      op_type: "list_mch",
    };
    let res = await post_axios("admin_oneself", "m_query", upMsg);
    if (!res) return;
    const receiveRows = res.data_rows.rows;
    setMch_list([...mch_list, ...receiveRows]);
  };
  // 商户筛选框-分页
  const mch_next_page = () => {
    setMch_page(mch_page + 1);
    get_mch_data(mch_page + 1);
  };

  function treeNodeItem(node) {
    const { TreeNode } = TreeSelect;
    if (node.children) {
      return (
        <TreeNode
          value={node.com_id}
          title={node.com}
          key={node.com_id}
          selectable={node.grade === 4}
          disabled={node.grade !== 4}
        >
          {node.children.map((child) => {
            return treeNodeItem(child);
          })}
        </TreeNode>
      );
    } else {
      return (
        <TreeNode
          value={node.com_id}
          title={node.com}
          key={node.com_id}
          selectable={node.grade === 4}
          disabled={node.grade !== 4}
        />
      );
    }
  }

  useEffect(() => {
    // 挂载后或者更新后的操作
    getData().then(() => {
      const tabBoxHeight =
        document.getElementsByClassName("account_split_plan")[0].scrollHeight;
      const tableHeight = tabBoxHeight - 96 - 70;
      setTableHeight(tableHeight);
    });
    if (user_grade < 70) {
      get_com_data();
    }
    get_mch_data();
  }, []);
  return (
    <>
      <div className="account_split_plan modules">
        <div className="screen_ipt">
          <div className="ipt_box">
            <div className="ipt_box_title">{t("assets.strategy_name")}</div>
            <Input
              placeholder=" "
              value={account_split_plan_name}
              size="small"
              allowClear={true}
              onChange={(e) => setAccount_split_plan_name(e.target.value)}
            />
          </div>
          <div className="ipt_box">
            <div className="ipt_box_title">{t("common.status")}</div>
            <Select
              size="small"
              placeholder=" "
              allowClear={true}
              options={[
                {
                  label: t("common.enable"),
                  value: "ENABLE",
                  key: "ENABLE",
                },
                {
                  label: t("common.disable"),
                  value: "DISABLE",
                  key: "DISABLE",
                },
              ]}
              value={account_split_plan_status}
              onChange={(value) => setAccount_split_plan_status(value)}
            />
          </div>
          {user_grade < 70 ? (
            <div className="ipt_box ipt_box_long">
              <div className="ipt_box_title">{t("market.organization")}</div>
              <TreeSelect
                value={com_ids_par}
                treeData={com_list}
                allowClear={true}
                size="small"
                multiple
                treeCheckStrictly={true}
                fieldNames={{
                  label: "com",
                  value: "com_id",
                  children: "children",
                }}
                placeholder=" "
                treeCheckable={true}
                onChange={(newValue) => setCom_ids_par(newValue)}
              />
            </div>
          ) : (
            ""
          )}
        </div>
        <div className="screen_btn">
          <div className="btn_box">
            {/* 添加 */}
            {menu_action.indexOf("m_add") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<PlusOutlined style={{ color: "#1677FF" }} />}
                onClick={() => edit_project_dialog_show("add")}
              >
                {text_check(user_power_lang["m_add"])}
              </Button>
            ) : (
              ""
            )}
            {/* 修改 */}
            {menu_action.indexOf("m_modify") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<EditOutlined style={{ color: "#1677FF" }} />}
                onClick={() => edit_project_dialog_show("change")}
              >
                {text_check(user_power_lang["m_modify"])}
              </Button>
            ) : (
              ""
            )}
            {/* 删除 */}
            {menu_action.indexOf("m_del") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<DeleteOutlined style={{ color: "#1677FF" }} />}
              >
                {text_check(user_power_lang["m_del"])}
              </Button>
            ) : (
              ""
            )}
            {/* 查询 */}
            {menu_action.indexOf("m_query") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<SearchOutlined style={{ color: "#1677FF" }} />}
                onClick={search_data}
              >
                {text_check(user_power_lang["m_query"])}
              </Button>
            ) : (
              ""
            )}
          </div>
          <div className="btn_box" style={{ width: "45vw" }}>
            {/* 添加 */}
            {menu_action.indexOf("m_add") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<PlusOutlined style={{ color: "#1677FF" }} />}
                onClick={() => edit_plan_mch_dialog("add")}
              >
                {text_check(user_power_lang["m_add"])}
              </Button>
            ) : (
              ""
            )}
            {/* 修改 */}
            {menu_action.indexOf("m_modify") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<EditOutlined style={{ color: "#1677FF" }} />}
                onClick={() => edit_plan_mch_dialog("change")}
              >
                {text_check(user_power_lang["m_modify"])}
              </Button>
            ) : (
              ""
            )}
          </div>
        </div>
        <div className="table_box">
          <div
            className="page-table"
            style={{
              width: "54.8vw",
            }}
          >
            <Table
              dataSource={account_split_plan_list}
              size="small"
              bordered
              columns={columns}
              rowKey="plan_id"
              virtual
              scroll={{
                y: tableHeight,
              }}
              onRow={(record) => {
                return {
                  onClick: () => tableRowClick(record), // 点击行
                };
              }}
              rowClassName={(record, index) => {
                if (record.plan_id == clickRowKey) {
                  return "row_clicked_style";
                }
              }}
              rowHoverable={false}
              pagination={{
                defaultCurrent: page,
                defaultPageSize: rows,
                size: "small",
                current: page,
                total: total,
                responsive: true,
                showTotal: (total) =>
                  text_check({
                    msg_cn: `共 ${total} 条`,
                    msg_en: `Total ${total} items`,
                  }),
                onChange: pageOnChange,
              }}
            />
          </div>

          <div
            className="noPage-table"
            style={{
              width: "45vw",
            }}
          >
            <Table
              dataSource={account_split_plan_mch_list}
              size="small"
              bordered
              columns={mchColumns}
              rowKey={(record) => record.plan_mch_name + record.mch_id}
              virtual
              scroll={{
                y: tableHeight,
              }}
              onRow={(record) => {
                return {
                  onClick: () => account_plan_mch_row_click(record), // 点击行
                };
              }}
              rowClassName={(record, index) => {
                if (record.plan_mch_id == clicked_plan_mch_id) {
                  return "row_clicked_style";
                }
              }}
              rowHoverable={false}
              pagination={false}
            />
          </div>
        </div>
      </div>

      <Modal
        title={editDialogtitle}
        open={editDialogshow}
        onOk={editConfirm}
        onCancel={() => setEditDialogshow(false)}
        classNames={{ body: "edit_dialog_body" }}
        maskClosable={false}
        destroyOnClose={true}
      >
        <div className="dialog_ipt_box">
          <div className="ipt_box_title">{t("assets.strategy_name")}</div>
          <Input
            placeholder=" "
            value={edit_account_split_plan_name}
            onChange={(e) => setEdit_account_split_plan_name(e.target.value)}
          />
        </div>
        <div className="dialog_ipt_box">
          <div className="ipt_box_title">{t("common.status")}</div>
          <Select
            placeholder=" "
            allowClear={false}
            options={[
              {
                label: t("common.enable"),
                value: "ENABLE",
                key: "ENABLE",
              },
              {
                label: t("common.disable"),
                value: "DISABLE",
                key: "DISABLE",
              },
            ]}
            value={edit_account_split_plan_status}
            onChange={(value) => setEdit_account_split_plan_status(value)}
          />
        </div>
        <div className="dialog_ipt_box">
          <div className="ipt_box_title">{t("market.organization")}</div>
          <TreeSelect
            value={edit_account_split_plan_com_id}
            placeholder=" "
            popupMatchSelectWidth={300}
            onSelect={(value, node, extra) => {
              return setEdit_account_split_plan_com_id(value);
            }}
          >
            {com_list.map((item) => {
              return treeNodeItem(item);
            })}
          </TreeSelect>
        </div>
      </Modal>

      <Modal
        title={edit_plan_mch_title}
        open={edit_plan_mch_show}
        onOk={edit_plan_mch_confirm}
        onCancel={() => setEdit_plan_mch_show(false)}
        classNames={{
          body: "edit_dialog_body account_split_plan_dialog",
          wrapper: "edit_800_style",
        }}
        maskClosable={false}
        destroyOnClose={true}
      >
        <div className="mch_arr_content">
          <div className="dialog_ipt_box dialog_ipt_box_long">
            <div className="ipt_box_title">{t("assets.commission_name")}</div>
            <Input
              placeholder=" "
              value={edit_plan_mch_name}
              onChange={(e) => setEdit_plan_mch_name(e.target.value)}
            />
          </div>
          <div className="dialog_ipt_box dialog_ipt_box_long">
            <div className="ipt_box_title">{t("system_manager.time")}</div>
            <RangePicker
              defaultValue={edit_plan_mch_time}
              onChange={(date, dateString) => {
                setEdit_plan_mch_time(date);
              }}
            />
          </div>
        </div>
        {edit_mch_arr.map((item, index) => {
          return (
            <div className="mch_arr_content" key={index}>
              <div className="dialog_ipt_box dialog_ipt_box_long">
                <div className="ipt_box_title">
                  {t("market.mch_new")} {index + 1}
                </div>
                <Select
                  placeholder=" "
                  defaultValue={item.mch_id}
                  options={mch_list}
                  fieldNames={{
                    label: "mch",
                    value: "mch_id",
                  }}
                  onChange={(value) => editMchChange(value, item, index)}
                  onPopupScroll={(event) => {
                    if (mch_list.length < mch_page * 20) {
                      console.log("没有更多商户的筛选数据了");
                      return;
                    }
                    const target = event.target;
                    const residueHeight =
                      target.scrollHeight -
                      target.scrollTop -
                      target.clientHeight;
                    if (residueHeight <= 50) {
                      mch_next_page();
                    }
                  }}
                  optionFilterProp="mch"
                />
              </div>
              <div className="dialog_ipt_box dialog_ipt_box_long">
                <div className="ipt_box_title">{t("assets.percentage")}</div>
                <Input
                  addonAfter="%"
                  defaultValue={item.share_proportion}
                  onChange={(e) =>
                    editProportionChange(e.target.value, item, index)
                  }
                />
              </div>
              <div className="add_icon remove_icon">
                <MinusCircleOutlined
                  style={{ fontSize: "20px" }}
                  onClick={() => remove_mch_child(index)}
                />
              </div>
            </div>
          );
        })}

        <div className="add_icon">
          <PlusCircleOutlined
            style={{ cursor: "pointer", fontSize: "20px" }}
            onClick={add_mch_child}
          />
        </div>
      </Modal>
    </>
  );
}
